<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" title="人员替换" />
    <!-- /导航栏 -->
    <van-form  ref="elform">
      <van-cell-group inset>
        <van-row gutter="23" >
          <van-col span="19">
           <van-field
              v-model="user.rpName"
              name="rpName"
              label="被替换人姓名"
              placeholder="被替换人姓名"
              :rules="[{ required: true, message: '请填写被替换人姓名' }]"
            />
          </van-col>
          <van-col span="5">
              <van-button  block type="primary" @click="getRpExaminer">
                查询
              </van-button>
          </van-col>

        </van-row>
        <van-field
          v-model="user.rpIdCode"
          is-link
          readonly
          name="rpIdCode"
          label="被替换人证件"
          placeholder="点击被替换人证件"
          @click="rpIdCodeShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="rpIdCodeShowPicker" position="bottom">
          <van-picker
            value-key="idCard"
            :columns="rpIdCodeList"
            :default-index="rpIdCodeShowPickerDefaultIndex"
            show-toolbar
            @confirm="onRpIdCodeConfirm"
            @cancel="rpIdCodeShowPicker = false"
          />
        </van-popup>
        <div v-if="isRpHasUser">
          <van-field
            v-model="user.name"
            name="userName"
            label="姓名"
            readonly
            placeholder="姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
          />
          <van-field
            v-model="user.idCard"
            readonly
            name="idCode"
            label="身份证号"
            placeholder="身份证号"
            :rules="[{ required: true, message: '请填写身份证号' }]"
          />

        <van-field
            v-model="user.phone"
            readonly
            name="mobile"
            label="手机号"
            placeholder="手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />

        <!--<van-field
            v-model="user.examScene"
            readonly
            name="examScene"
            label="替换场次"
            placeholder="替换场次"
            :rules="[{ required: true, message: '请填写替换场次' }]"
          />-->
        </div>
        <div v-else>

          <van-row gutter="23" >
          <van-col span="19">
            <van-field
              v-model="user.idCard"
              name="idCode"
              label="身份证号"
              placeholder="身份证号"
              :rules="[{ required: true, message: '请填写身份证号' }]"
            />
          </van-col>
          <van-col span="5">
              <van-button  block type="primary" @click="getUserInfoForIdcardandGrantid">
                查询
              </van-button>
          </van-col>

        </van-row>

          <van-field
            v-model="user.name"
            name="userName"
            label="姓名"
            placeholder="姓名"
            :rules="[{ required: true, message: '请填写姓名' }]"
          />

        <van-field
            v-model="user.phone"
            name="mobile"
            label="手机号"
            placeholder="手机号"
            :rules="[{ required: true, message: '请填写手机号' }]"
          />
        </div>
        <van-field v-if="isImg" name='userImg' label="证件照" colon >
          <template #input>
             <van-image style="width:206px;height:244px;" :src="user.staffImg ? user.staffImg:require('@/assets/icon/tx.png')"/>
          </template>
        </van-field>
       <van-row v-if="isImg" gutter="20" style="margin-top:2px">
          <van-col span="10">
          </van-col>
          <van-col span="10">
              <van-uploader :after-read="afterRead" :max-count="1" accept="image/png, image/jpeg">
                <van-button icon="add-o">上传证件照</van-button>
              </van-uploader>
          </van-col>
        </van-row>
        <van-field
          v-model="user.sexLabel"
          is-link
          readonly
          name="userSex"
          label="性别"
          placeholder="点击选择性别"
          @click="sexShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="sexShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="sexList"
            :default-index="sexShowPickerDefaultIndex"
            show-toolbar
            @confirm="onSexConfirm"
            @cancel="sexShowPicker = false"
          />
        </van-popup>

        <van-field
          v-model="user.postLabel"
          is-link
          name="userPost"
          label="职务"
          placeholder="点击选择职务"
          @click="postShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="postShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="postList"
            :default-index="postShowPickerDefaultIndex"
            show-toolbar
            @confirm="onPostConfirm"
            @cancel="postShowPicker = false"
          />
        </van-popup>
         <van-field
          v-model="user.technicalTitleLabel"
          is-link
          name="userTechnicalTitle"
          label="职称"
          placeholder="点击选择职称"
          @click="technicalTitleShowPicker = true"
          arrow-direction="down" center
        />
        <van-popup v-model:show="technicalTitleShowPicker" position="bottom">
          <van-picker
            value-key="dictLabel"
            :columns="technicalTitleList"
            :default-index="technicalTitleShowPickerDefaultIndex"
            show-toolbar
            @confirm="onTechnicalTitleConfirm"
            @cancel="technicalTitleShowPicker = false"
          />
        </van-popup>
        <van-field
          v-model="user.bankCode"
          name="userBankCode"
          label="银行卡号"
          :rules="userFormRules.bankCard"
          placeholder="请输入银行卡号"
        />

        <van-field
          v-model="user.openBank"
          name="userOpenBank"
          label="开户行"
          placeholder="请输入开户行"
          :rules="[{ required: true, message: '请输入开户行' }]"
        />
        <van-field
          v-model="user.bankMobile"
          name="userBankMobile"
          label="对应手机号"
          :rules="userFormRules.mobile"
          placeholder="请输入对应手机号"
        />

      </van-cell-group>

      <van-row gutter="24" style="margin-top:16px">
        <van-col span="1">
        </van-col>
        <van-col span="22">
          <van-button  block type="primary" @click="onSubmit" ref="btnSubmit">
            提交
          </van-button>
        </van-col>
        <van-col span="1">
        </van-col>
      </van-row>
    </van-form>
    <!-- /登录表单 -->
  </div>
</template>
<script>
function getUrlKey(name){//获取url 参数

  return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;

}

function getCodeApi(state){//获取code

  let urlNow=encodeURIComponent(window.location.href);

  let scope='snsapi_base'; //snsapi_userinfo //静默授权 用户无感知

  let appid='wx304b179d66268e6b';
  appid = 'wx8c5a10694bf703f1';
  var num=Math.floor(Math.random()*10000+1);
  let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=${state}&no=${num}#wechat_redirect`;
  window.location.replace(url);

}

import { getOpenId } from "@/api/login";
import { querySignature,uploadOSSFile,getSignature } from "@/api/oss";
import { getDicts,updGrExaminer,getExaminerInfoForOpenId,getRpExaminerList,examinerReplace,examinerReplaceComplex,getUserInfoForIdcardandGrantid }
 from "@/api/grantexaminer/grantexaminer";
import uuidv1 from "uuid/v1"
import { decrypt,encrypt,ossType } from '@/api/aesUtil'
export default {
  name: 'LoginIndex',
  components: {},
  props: {},
  data () {
    return {
      rpIdCodeShowPicker:false,
      rpIdCodeShowPickerDefaultIndex:0,
      sceneId: undefined,
      openId: undefined,
      //当前要替换的用户信息是否存在
      isRpHasUser:false,
      isImg:false,
      grantId:'',
      loginInfo:{},
      sexShowPicker:false,
      nationShowPicker:false,
      politicalShowPicker:false,
      technicalTitleShowPicker:false,
      postShowPicker:false,
      sexShowPickerDefaultIndex:0,
      nationShowPickerDefaultIndex:0,
      politicalShowPickerDefaultIndex:0,
      technicalTitleShowPickerDefaultIndex:0,
      postShowPickerDefaultIndex:0,
      user: {
        grantId:undefined,
        name: '',
        idCard: '',
        phone: '',
        rpName: '',
        rpIdCode: '',
        rpExaminerId: undefined,
        examinerId: undefined,
        examinerSceneId: undefined,
        sceneId: undefined,
        staffImg:'',
        sex: '',
        sexLabel: '',
        nation: '',
        nationLabel: '',
        political: '',
        politicalLabel: '',
        post: '',
        postLabel: '',
        technicalTitle: '',
        technicalTitleLabel: '',
        bankCode:'',
        openBank:'',
        bankMobile:''
      },
      rpIdCodeList:[],
      sexList:[],
      nationList:[],
      politicalList:[],
      technicalTitleList:[],
      postList:[],
      userFormRules: {
        mobile: [{
          required: true,
          message: '手机号不能为空'
        }, {
          pattern: /^1[3|5|7|8|9]\d{9}$/,
          message: '手机号格式错误'
        }],
        code: [{
          required: true,
          message: '验证码不能为空'
        }, {
          pattern: /^\d{6}$/,
          message: '验证码格式错误'
        }],
        bankCard: [{
          required: true,
          message: '银行卡号为空'
        }, {
          pattern: /^([1-9]{1})(\d{15}|\d{16}|\d{17}|\d{18}|\d{19})$/,
          message: '银行卡号格式错误'
        }]
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    //grantId  sceneId
    this.sceneId = this.$route.query.sceneId ? this.$route.query.sceneId : undefined
    if (this.sceneId === undefined) {
      this.$toast.fail({
        message: '末传入签到信息，无法进行下一步操作',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      });
    }
    let userAgent = this.isAlipayOrWechat();
    if ("wechat" === userAgent) {
      let code=getUrlKey("code");//获取url参数code
      if(code) { //拿到code， code传递给后台接口换取opend
        let that = this;
        if(this.openId===undefined)
        {
          getOpenId(code).then(res=>{
            if(res.code==200){
              this.openId = res.msg;
              this.weixinLogin();
            }else{
              getDicts('sys_user_sex').then(res=>{
                if(res.code===200){
                  this.sexList = res.data
                }
                else{
                  this.sexList = []
                }
              })
              getDicts('technical_title').then(res=>{
                if(res.code===200){
                  this.technicalTitleList = res.data
                }
                else{
                  this.technicalTitleList = []
                }

              })
              getDicts('sys_post').then(res=>{
                if(res.code===200){
                  this.postList = res.data
                }
                else{
                  this.postList = []
                }

              })
            }
          }).catch(err=>{
            console.log(err);
          })
        }else {
          this.weixinLogin();
        }
      }else{
        getCodeApi("_wx");
      }
    }
    else{
      getDicts('sys_user_sex').then(res=>{
        if(res.code===200){
          this.sexList = res.data
        }
        else{
          this.sexList = []
        }
      })
      getDicts('technical_title').then(res=>{
        if(res.code===200){
          this.technicalTitleList = res.data
        }
        else{
          this.technicalTitleList = []
        }

      })
      getDicts('sys_post').then(res=>{
        if(res.code===200){
          this.postList = res.data
        }
        else{
          this.postList = []
        }

      })
    }

  },
  mounted () {
    this.initOss();
  },
  methods: {
    onSexConfirm(val) {
      this.sexShowPicker = false
      this.user.sex = val.dictValue
      this.user.sexLabel = val.dictLabel
    },
    onNationConfirm(val) {
      this.nationShowPicker = false
      this.user.nation = val.dictValue
      this.user.nationLabel = val.dictLabel
    },
    onPoliticalConfirm(val) {
      this.politicalShowPicker = false
      this.user.political = val.dictValue
      this.user.politicalLabel = val.dictLabel
    },
    onTechnicalTitleConfirm(val) {
      this.technicalTitleShowPicker = false
      this.user.technicalTitle = val.dictValue
      this.user.technicalTitleLabel = val.dictLabel
    },

    onPostConfirm(val) {
      this.postShowPicker = false
      this.user.post = val.dictValue
      this.user.postLabel = val.dictLabel
    },
    weixinLogin(){
      let sceneQuery = {};
      sceneQuery['openId'] = this.openId;
      sceneQuery['sceneId'] = this.sceneId;
      getExaminerInfoForOpenId(sceneQuery).then(res=>{
        this.user.idCard = res.data.idcard;
        this.user.name = res.data.name;
        this.user.phone = res.data.phone;
        this.user.examinerId = res.data.examinerId;
        if(res.data.examinerId!=null)
        {
          this.isRpHasUser = true;
        }
        else
        {
          this.isRpHasUser = false;
          getDicts('sys_user_sex').then(res=>{
            if(res.code===200){
              this.sexList = res.data
            }
            else{
              this.sexList = []
            }
          })
          getDicts('technical_title').then(res=>{
            if(res.code===200){
              this.technicalTitleList = res.data
            }
            else{
              this.technicalTitleList = []
            }

          })
          getDicts('sys_post').then(res=>{
            if(res.code===200){
              this.postList = res.data
            }
            else{
              this.postList = []
            }

          })
        }
      }).catch(err=>{
        //this.$toast.fail(err.toString());
        this.isRpHasUser = false;
        getDicts('sys_user_sex').then(res=>{
          if(res.code===200){
            this.sexList = res.data
          }
          else{
            this.sexList = []
          }
        })
        getDicts('technical_title').then(res=>{
          if(res.code===200){
            this.technicalTitleList = res.data
          }
          else{
            this.technicalTitleList = []
          }

        })
        getDicts('sys_post').then(res=>{
          if(res.code===200){
            this.postList = res.data
          }
          else{
            this.postList = []
          }

        })
      })
    },
    onRpIdCodeConfirm(val){
      this.user.rpIdCode = val.idCard;
      this.user.rpExaminerId = val.examinerId;
      this.user.examinerSceneId = val.id;
      this.rpIdCodeShowPicker = false;

    },
    getRpExaminer(){
      let sceneQuery = {};
      sceneQuery['examinerName'] = this.user.rpName;
      sceneQuery['sceneId'] = this.sceneId;
      getRpExaminerList(sceneQuery).then(res=>{
        this.rpIdCodeList = res.data;
        if(this.rpIdCodeList.length>0)
        {
          this.user.rpIdCode = this.rpIdCodeList[0].idCard;
          this.grantId = '' + this.rpIdCodeList[0].grantId;
          this.user.rpExaminerId = this.rpIdCodeList[0].examinerId;
          this.user.examinerSceneId = this.rpIdCodeList[0].id;
          this.user.grantId = this.grantId;


          if(this.rpIdCodeList[0].grantType!=null&&this.rpIdCodeList[0].grantType.indexOf('Img')>=0)
          {
            this.isImg = true;
          }
          else{
            this.isImg = false;
          }
        }else
        {
          this.$toast.fail('人员信息不存在')
        }
        this.rpIdCodeShowPickerDefaultIndex = 0;
      })
    },
    getUserInfoForIdcardandGrantid(){
      let examQuery = {};
      examQuery['idcard'] = this.user.idCard;
      examQuery['grantId'] = this.grantId;
      getUserInfoForIdcardandGrantid(examQuery).then(res=>{
        //用户信息存在
        if(res.data.examinerId!=null)
        {

           this.user.name = res.data.name;
           this.user.phone = res.data.phone;
           this.user.examinerId = res.data.examinerId;
           this.user.staffImg = res.data.photoUrl;
           this.user.sex = res.data.sex==null?'':res.data.sex;
           if(this.user.sex!='')
           {
             this.sexList.forEach((item,index)=>
              {
                if(item.dictValue==this.user.sex){
                  this.user.sexLabel = item.dictLabel
                  this.sexShowPickerDefaultIndex = index
                  return
                }
              })
           }
           this.user.post = res.data.post==null?'':res.data.post;
           if(this.user.post!='')
           {
             this.postList.forEach((item,index)=>
              {
                if(item.dictValue==this.user.post){
                  this.user.postLabel = item.dictLabel
                  this.postShowPickerDefaultIndex = index
                  return
                }
              })
           }
           this.user.technicalTitle = res.data.technicalTitle==null?'':res.data.technicalTitle;
           if(this.user.technicalTitle!='')
           {
             this.technicalTitleList.forEach((item,index)=>
              {
                if(item.dictValue==this.user.technicalTitle){
                  this.user.technicalTitleLabel = item.dictLabel
                  this.technicalTitleShowPickerDefaultIndex = index
                  return
                }
              })
           }
           this.user.bankCode = res.data.blankCark==null?'':res.data.blankCark;
           this.user.openBank = res.data.depositName==null?'':res.data.depositName;
           this.user.bankMobile = res.data.blankPhone==null?'':res.data.blankPhone;

        }else{
           this.user.name = '';
           this.user.phone = '';
           this.user.examinerId = null;
           this.user.staffImg = '';
           this.user.sex = '';
           this.user.sexLabel = '';

           this.user.post = '';
           this.user.postLabel = '';

           this.user.technicalTitle = '';
           this.user.technicalTitleLabel = '';

           this.user.bankCode = '';
           this.user.openBank = '';
           this.user.bankMobile = '';
        }

      })
    }
    ,
    initOss () {
      let that = this
      querySignature("init").then(res=>{
        if (res.code === 0 && res.data.tyCloudFlag=='1') {
          that.client = new ObsClient({
              access_key_id: res.data.accessid,
              secret_access_key:  decrypt(res.data.signature),
              server : res.data.endPoint
          });
        }
      })
    },
    async afterRead(info) {
      const { file } = info
      let that = this
      try {
        const signRes = await querySignature("image")
        if (signRes.code === 0) {
            if(signRes.data.tyCloudFlag=='0'){
              const filename = file.name;
              const size = file.size;
              console.log("signRes",signRes,filename)
              const fileExt = filename.split(".");
              const uuid = uuidv1();
              let formData = new FormData();
              //注意formData里append添加的键的大小写
              formData.append('key', signRes.data.dir + uuid + "." + fileExt[1]); //存储在oss的文件路径
              formData.append('OSSAccessKeyId', signRes.data.accessid); //accessKeyId
              formData.append('policy', signRes.data.policy); //policy
              formData.append('Signature', signRes.data.signature); //签名
              //formData.append('callback', signRes.callback); //回调
              formData.append('success_action_status', 200); //成功后返回的操作码
              //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
              formData.append("file", file);

              var res = await uploadOSSFile(signRes.data.host, formData);
              const imageUrl = signRes.data.host.replaceAll('http://','https://')+'/'+signRes.data.dir + uuid + "." + fileExt[1];


              this.user.staffImg = imageUrl


              this.$toast.success('上传成功')
            }else{

              const filename = file.name;
              const size = file.size;

              const fileExt = filename.split(".");
              const uuid = uuidv1();

              var params = {
                Body: file,
                Bucket: signRes.data.bucket,
                Key: signRes.data.dir + uuid + "." + fileExt[1]
              }
              that.client.putObject(params, function (err, data) {
                if (err) {
                  that.$toast.success('上传失败')
                } else {

                  const imageUrl = signRes.data.host+'/'+signRes.data.dir + uuid + "." + fileExt[1];

                  that.user.staffImg = imageUrl

                  that.$toast.success('上传成功')
                }
              })
            }
        }
      }catch (e) {
        console.log(e);
        this.$toast.fail('上传失败')
      }
    },
    oversize(e) {
      this.$toast.fail("图片过大！");
    },
    async onSubmit () {
      let that = this;
      this.$refs.elform.validate().then((result)=>{
        if(result==null)
        {
          //替换者的用户信息存在，直接替换
          if(that.isRpHasUser)
          {
              that.user.sceneId = this.sceneId;
              // 3. 提交表单请求登录
              that.$toast.loading({
                message: '保存中...',
                forbidClick: true, // 禁用背景点击
                duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
              })
              try {
                examinerReplace(that.user).then(res=>{

                  if(res.code===200){
                    this.$toast.clear();
                    this.$refs.btnSubmit.setAttribute('disabled',true);
                    swal({
                        title: '提示',
                        text: '替换成功,请关闭页面',
                        allowOutsideClick:false,
                        icon: "success",
                        button: {
                          text: "确认",
                          closeModal: true
                        }
                    })
                  }else{
                    that.$toast.fail(res.msg)
                  }
                }).catch(err=>{

                  that.$toast.fail('替换失败，'+err.message)
                })
              } catch (err) {
                that.$toast.fail('替换失败，'+err.message)
              }
          }else
          {
            this.user.sceneId = this.sceneId;
              // 3. 提交表单请求登录
              that.$toast.loading({
                message: '保存中...',
                forbidClick: true, // 禁用背景点击
                duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
              })
              try {
                examinerReplaceComplex(that.user).then(res=>{
                  if(res.code===200){
                    this.$refs.btnSubmit.setAttribute('disabled',true);
                    this.$toast.clear();
                    swal({
                        title: '提示',
                        text: '替换成功,请关闭页面',
                        allowOutsideClick:false,
                        icon: "success",
                        button: {
                          text: "确认",
                          closeModal: true
                        }
                    })
                  }else{
                    that.$toast.fail(res.msg)
                  }
                }).catch(err=>{

                  that.$toast.fail('替换失败，'+err.message)
                })
              } catch (err) {
                that.$toast.fail('替换失败，'+err.message)
              }
          }
        }

      })


    },
    isAlipayOrWechat(){
      var userAgent = window.navigator.userAgent.toLowerCase();
      if (userAgent.match(/Alipay/i) == "alipay") {
        //alert("支付宝浏览器");
        return "alipay";

      } else if (userAgent.match(/MicroMessenger/i) == "micromessenger") {
        // alert("微信浏览器");
        return "wechat";
      } else {    return "";  }
    }
  }
}
</script>

<style scoped lang="less">

.login-container {
  .toutiao {
    font-size: 37px;
  }
  .send-sms-btn {
    width: 152px;
    height: 46px;
    line-height: 46px;
    background-color: #ededed;
    font-size: 22px;
    color: #666;
  }
  .login-btn-wrap {
    padding: 53px 33px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
    }
  }
}
</style>
